/*
 * 
 * Copyright 2010 David H Pollack
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 * 
 * 
 */

package com.dhpollack.rotogss.servlets;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.oauth.OAuthException;

import com.dhpollack.rotogss.data.AppConfig;
import com.dhpollack.rotogss.helper.AppHelper;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.simpleyql.Api;
import com.simpleyql.ApiFactory;

/**
 * @author davidpl
 *
 */
public class YahooOAuthStartServlet extends HttpServlet {
	
	private static final long serialVersionUID = -3420136789426781564L;

	protected void service(HttpServletRequest req, HttpServletResponse resp) 
	throws IOException {
		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        
        if(user != null) {
    		AppConfig appConfig = AppHelper.get();
    		
    		Api api = ApiFactory.getApiInstance(
    	            appConfig.getYahooConsumerKey(),
    	            appConfig.getYahooConsumerSecret(),
    	            appConfig.getBaseUrl() + "/simpleyqlcallback/",
    	            false, null);
    	    try {
    			api.askAuthorization(req, resp, appConfig.getBaseUrl() + "/yahooauthreturn");
    		} catch (OAuthException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		
    		
        } else {
            resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
        }
		
	}


}
